<template>
  <!-- 
    Homepage风格的仪表板视图
    主要功能：
    1. 搜索引擎区域 - 支持Google和必应搜索
    2. 组件管理区域 - 显示用户已添加的组件
    3. 组件商店 - 用于添加新组件
    4. 组件配置 - 配置已添加的组件
  -->
  <div class="homepage-container">
    <!-- 顶部用户工具栏 -->
    <div class="top-toolbar">
      <div class="toolbar-left">
        <!-- 用户信息 -->
        <el-dropdown @command="handleCommand" class="user-dropdown">
          <div class="user-info">
            <el-avatar :size="32" :src="userAvatar">
              {{ authStore.user?.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <span class="username">{{ authStore.user?.username }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                {{ t('dashboard.userMenu.profile') }}
              </el-dropdown-item>
              <el-dropdown-item command="user-role-permission" v-permission="'user:read'">
                <el-icon><User /></el-icon>
                {{ t('dashboard.userMenu.userManagement') }}
              </el-dropdown-item>
              <el-dropdown-item divided command="settings">
                <el-icon><Setting /></el-icon>
                {{ t('dashboard.userMenu.settings') }}
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                {{ t('dashboard.userMenu.logout') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      
      <div class="toolbar-right">
        <!-- 主题切换器 -->
        <el-tooltip :content="themeStore.theme === 'light' ? t('dashboard.theme.dark') : themeStore.theme === 'dark' ? t('dashboard.theme.light') : t('dashboard.theme.auto')" placement="bottom">
          <el-button
            type="text"
            @click="toggleTheme"
            class="toolbar-button"
          >
            <el-icon :size="18">
              <Sunny v-if="themeStore.theme === 'light'" />
              <Moon v-else />
            </el-icon>
          </el-button>
        </el-tooltip>
        
        <!-- 语言切换器 -->
        <el-dropdown @command="changeLanguage" class="language-dropdown">
          <el-button type="text" class="toolbar-button">
            <el-icon :size="18">
              <LanguageIcon />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="zh-CN" :class="{ 'is-active': locale === 'zh-CN' }">
                <span class="flag">🇨🇳</span> 中文
              </el-dropdown-item>
              <el-dropdown-item command="en-US" :class="{ 'is-active': locale === 'en-US' }">
                <span class="flag">🇺🇸</span> English
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 搜索引擎区域 -->
    <div class="search-section">
      <div class="search-container">
        <!-- 搜索栏标题 -->
        <div class="search-title">
          <h1>{{ t('dashboard.quickSearch') }}</h1>
          <p>{{ t('dashboard.quickSearchDesc') }}</p>
        </div>
        
        <!-- 融合的搜索栏 -->
        <div class="unified-search-bar">
          <!-- 搜索引擎切换器 -->
          <el-dropdown @command="changeSearchEngine" class="search-engine-dropdown">
            <div class="engine-selector">
              <img :src="currentEngine.icon" :alt="currentEngine.label" class="engine-icon" />
              <span class="engine-name">{{ currentEngine.label }}</span>
              <el-icon><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="engine in searchEngines"
                  :key="engine.value"
                  :command="engine.value"
                  :class="{ 'is-active': selectedEngine === engine.value }"
                >
                  <div class="engine-option">
                    <img :src="engine.icon" :alt="engine.label" class="engine-icon" />
                    <span>{{ engine.label }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <!-- 搜索输入框 -->
          <el-input
            v-model="searchQuery"
            size="large"
            :placeholder="currentEngine.placeholder"
            class="search-input"
            @keyup.enter="performSearch"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <!-- 搜索按钮 -->
          <el-button type="primary" size="large" class="search-button" @click="performSearch">
            {{ t('common.search') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 快速添加组件区域 -->
    <div class="quick-add-section">
      <!-- 区域标题和添加按钮 -->
      <div class="section-header">
        <h2>{{ t('dashboard.myWidgets') }}</h2>
        <el-button type="primary" size="small" @click="showWidgetStore = true">
          <el-icon><Plus /></el-icon>
          {{ t('dashboard.addWidget') }}
        </el-button>
      </div>
      
      <!-- 加载状态显示 -->
      <div v-if="widgetStore.loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <!-- 空状态显示 -->
      <div v-else-if="enabledWidgets.length === 0" class="empty-container">
        <el-empty :description="t('dashboard.noWidgetsYet')">
          <el-button type="primary" @click="showWidgetStore = true">
            {{ t('dashboard.addFirstWidget') }}
          </el-button>
        </el-empty>
      </div>

      <!-- 组件网格显示 -->
      <div v-else class="widgets-grid">
        <div 
          v-for="userWidget in enabledWidgets" 
          :key="userWidget.id"
          class="widget-item"
        >
          <!-- 组件头部信息 -->
          <div class="widget-header">
            <div class="widget-title">
              <el-icon :size="20" :color="getWidgetColor(userWidget.widget?.category)">
                <component :is="getWidgetIcon(userWidget.widget?.category)" />
              </el-icon>
              <span>{{ userWidget.widget?.name }}</span>
            </div>
            <!-- 组件操作按钮 -->
            <div class="widget-actions">
              <el-button 
                size="small" 
                type="primary"
                @click="showWidgetConfig(userWidget)"
                :title="t('dashboard.configureWidget')"
              >
                <el-icon><Setting /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                @click="toggleWidget(userWidget)"
                :title="userWidget.is_enabled ? t('dashboard.disableWidget') : t('dashboard.enableWidget')"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
          <!-- 组件内容信息 -->
          <div class="widget-content">
            <div class="widget-description">
              {{ userWidget.widget?.description }}
            </div>
            <div class="widget-info">
              <el-tag size="small" :type="getWidgetTagType(userWidget.widget?.category)">
                {{ userWidget.widget?.category }}
              </el-tag>
              <span class="widget-version">v{{ userWidget.widget?.version }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 组件商店对话框 -->
    <el-dialog
      v-model="showWidgetStore"
      :title="t('dashboard.widgetStore')"
      width="80%"
      :before-close="handleWidgetStoreClose"
    >
      <WidgetStore @select="addWidgetToDashboard" />
    </el-dialog>

    <!-- 组件配置对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      :title="`配置 ${currentWidget?.widget?.name}`"
      width="600px"
    >
      <WidgetConfig 
        v-if="currentWidget"
        :widget="currentWidget"
        @save="saveWidgetConfig"
        @cancel="showConfigDialog = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * Homepage风格的仪表板组件
 * 
 * 功能特性：
 * 1. 集成搜索引擎（Google和必应）
 * 2. 组件管理系统
 * 3. 响应式设计
 * 4. 现代化UI设计
 */

import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useWidgetStore } from '@/stores/widget'
import { useThemeStore } from '@/stores/theme'
import { useI18n } from 'vue-i18n'
import { Sunny, Moon, CaretBottom, User, Setting, SwitchButton, Search } from '@element-plus/icons-vue'
import WidgetStore from '@/components/WidgetStore.vue'
import WidgetConfig from '@/components/WidgetConfig.vue'
import LanguageIcon from '@/components/icons/LanguageIcon.vue'
import type { UserWidget } from '@/stores/widget'

// ==================== 依赖注入 ====================
const router = useRouter()
const authStore = useAuthStore()
const widgetStore = useWidgetStore()
const themeStore = useThemeStore()
const { t, locale } = useI18n()

// ==================== 搜索引擎状态 ====================
/** 搜索查询内容 */
const searchQuery = ref('')
/** 当前选择的搜索引擎 */
const selectedEngine = ref('google')

// 搜索引擎配置
const searchEngines = [
  {
    value: 'google',
    label: t('dashboard.searchEngines.google'),
    icon: '',
    placeholder: t('dashboard.searchEngines.searchGoogle'),
    url: 'https://www.google.com/search?q={query}'
  },
  {
    value: 'bing',
    label: t('dashboard.searchEngines.bing'),
    icon: '',
    placeholder: t('dashboard.searchEngines.searchBing'),
    url: 'https://www.bing.com/search?q={query}'
  }
]

// 当前搜索引擎
const currentEngine = computed(() => 
  searchEngines.find(engine => engine.value === selectedEngine.value) || searchEngines[0]
)

// 用户头像
const userAvatar = ref('')

// 对话框状态
const showWidgetStore = ref(false)
const showConfigDialog = ref(false)
const currentWidget = ref<UserWidget | null>(null)

// 计算属性
const enabledWidgets = computed(() => widgetStore.getEnabledUserWidgets())

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化数据
 * 获取用户组件列表和可用组件列表
 */
onMounted(async () => {
  await Promise.all([
    widgetStore.fetchUserWidgets(),
    widgetStore.fetchWidgets()
  ])
})

// ==================== 搜索功能 ====================
/**
 * 执行搜索操作
 * 在新标签页中打开搜索引擎结果页面
 */
function performSearch() {
  if (!searchQuery.value.trim()) return
  
  const searchUrl = currentEngine.value.url.replace('{query}', encodeURIComponent(searchQuery.value))
  window.open(searchUrl, '_blank')
}

// ==================== 主题和语言功能 ====================
/**
 * 切换主题
 */
function toggleTheme() {
  const currentTheme = themeStore.theme
  if (currentTheme === 'light') {
    themeStore.setTheme('dark')
  } else if (currentTheme === 'dark') {
    themeStore.setTheme('auto')
  } else {
    themeStore.setTheme('light')
  }
}

/**
 * 切换语言
 * @param lang - 语言代码
 */
function changeLanguage(lang: string) {
  locale.value = lang
  localStorage.setItem('language', lang)
}

/**
 * 切换搜索引擎
 * @param engine - 搜索引擎值
 */
function changeSearchEngine(engine: string) {
  selectedEngine.value = engine
}

/**
 * 处理用户下拉菜单命令
 * @param command - 命令
 */
async function handleCommand(command: string) {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'user-role-permission':
      router.push('/user-role-permission')
      break
    case 'settings':
      ElMessage.info(t('messages.settingsDeveloping'))
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          t('layout.logoutConfirm'),
          t('common.info'),
          {
            confirmButtonText: t('common.confirm'),
            cancelButtonText: t('common.cancel'),
            type: 'warning'
          }
        )
        
        authStore.logout()
        ElMessage.success(t('layout.logoutSuccess'))
        router.push('/login')
      } catch {
        // 用户取消操作
      }
      break
  }
}

// ==================== 组件管理功能 ====================
/**
 * 添加组件到仪表板
 * @param widgetId - 要添加的组件ID
 */
async function addWidgetToDashboard(widgetId: number) {
  try {
    await widgetStore.addUserWidget(widgetId)
    showWidgetStore.value = false
    ElMessage.success(t('dashboard.widgetAdded'))
  } catch (error: any) {
    ElMessage.error(error.message || t('dashboard.operationFailed'))
  }
}

/**
 * 显示组件配置对话框
 * @param userWidget - 要配置的用户组件
 */
function showWidgetConfig(userWidget: UserWidget) {
  currentWidget.value = userWidget
  showConfigDialog.value = true
}

/**
 * 保存组件配置
 * @param config - 组件配置数据
 */
async function saveWidgetConfig(config: any) {
  if (!currentWidget.value) return
  
  try {
    await widgetStore.updateUserWidget(currentWidget.value.id, config)
    showConfigDialog.value = false
    ElMessage.success(t('dashboard.widgetConfigSaved'))
  } catch (error: any) {
    ElMessage.error(error.message || t('dashboard.operationFailed'))
  }
}

/**
 * 切换组件启用/禁用状态
 * @param userWidget - 要切换状态的组件
 */
async function toggleWidget(userWidget: UserWidget) {
  try {
    await widgetStore.toggleUserWidget(userWidget.id)
    ElMessage.success(t('dashboard.widgetOperationSuccess', { 
    name: userWidget.widget?.name, 
    status: userWidget.is_enabled ? t('dashboard.enableWidget') : t('dashboard.disableWidget') 
  }))
  } catch (error: any) {
    ElMessage.error(error.message || t('dashboard.operationFailed'))
  }
}

/**
 * 关闭组件商店对话框
 */
function handleWidgetStoreClose() {
  showWidgetStore.value = false
}

// ==================== 组件UI辅助函数 ====================
/**
 * 根据组件分类获取对应的图标
 * @param category - 组件分类
 * @returns 图标组件名称
 */
function getWidgetIcon(category?: string) {
  const iconMap: Record<string, string> = {
    'default': 'Grid',
    'system': 'Setting',
    'tool': 'Tool',
    'dashboard': 'Monitor',
    'communication': 'Message',
    'file': 'Document',
    'entertainment': 'VideoPlay'
  }
  return iconMap[category || 'default'] || 'Grid'
}

/**
 * 根据组件分类获取对应的颜色
 * @param category - 组件分类
 * @returns 颜色值
 */
function getWidgetColor(category?: string) {
  const colorMap: Record<string, string> = {
    'default': '#409EFF',
    'system': '#909399',
    'tool': '#E6A23C',
    'dashboard': '#67C23A',
    'communication': '#8B5CF6',
    'file': '#F56C6C',
    'entertainment': '#FF6B6B'
  }
  return colorMap[category || 'default'] || '#409EFF'
}

/**
 * 根据组件分类获取对应的标签类型
 * @param category - 组件分类
 * @returns Element Plus标签类型
 */
function getWidgetTagType(category?: string) {
  const typeMap: Record<string, string> = {
    'default': 'primary',
    'system': 'info',
    'tool': 'warning',
    'dashboard': 'success',
    'communication': 'danger',
    'file': 'danger',
    'entertainment': 'danger'
  }
  return typeMap[category || 'default'] || 'primary'
}
</script>

<style scoped>
/* ==================== 主容器样式 ==================== */
.homepage-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
  padding: 0;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* ==================== 顶部工具栏样式 ==================== */
.top-toolbar {
  padding: 24px 32px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-dropdown .user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 10px 16px;
  border-radius: 8px;
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(148, 163, 184, 0.2);
  transition: all 0.2s ease;
}

.user-dropdown .user-info:hover {
  background: rgba(51, 65, 85, 0.9);
  border-color: rgba(148, 163, 184, 0.3);
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #e2e8f0;
}

.toolbar-button {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(148, 163, 184, 0.2);
  color: #94a3b8;
  transition: all 0.2s ease;
}

.toolbar-button:hover {
  background: rgba(51, 65, 85, 0.9);
  border-color: rgba(148, 163, 184, 0.3);
  color: #e2e8f0;
}

.language-dropdown .flag {
  margin-right: 8px;
}

.language-dropdown .is-active {
  color: #3b82f6;
  font-weight: 600;
}

/* ==================== 搜索区域样式 ==================== */
.search-section {
  padding: 60px 20px 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.search-container {
  width: 100%;
  max-width: 680px;
}

.search-title {
  text-align: center;
  margin-bottom: 32px;
}

.search-title h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  color: #f1f5f9;
  letter-spacing: -0.02em;
}

.search-title p {
  margin: 0;
  font-size: 16px;
  color: #94a3b8;
  line-height: 1.5;
}

.unified-search-bar {
  display: flex;
  align-items: center;
  background: rgba(30, 41, 59, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  padding: 6px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(148, 163, 184, 0.2);
}

.search-engine-dropdown {
  margin-right: 4px;
}

.engine-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 14px;
  border-radius: 8px;
  background: rgba(51, 65, 85, 0.8);
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 100px;
  border: 1px solid rgba(148, 163, 184, 0.1);
}

.engine-selector:hover {
  background: rgba(71, 85, 105, 0.9);
  border-color: rgba(148, 163, 184, 0.2);
}

.engine-icon {
  width: 18px;
  height: 18px;
}

.engine-name {
  font-size: 13px;
  font-weight: 500;
  color: #cbd5e1;
  flex: 1;
}

.search-engine-dropdown .engine-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-engine-dropdown .is-active {
  color: #3b82f6;
  font-weight: 600;
}

.search-input {
  flex: 1;
  margin: 0 6px;
}

.search-input .el-input__wrapper {
  box-shadow: none;
  background: transparent;
}

.search-input .el-input__inner {
  color: #e2e8f0;
  font-size: 15px;
}

.search-input .el-input__inner::placeholder {
  color: #64748b;
}

.search-button {
  padding: 0 20px;
  border-radius: 8px;
  font-weight: 500;
  height: 44px;
}

/* ==================== 快速添加组件区域样式 ==================== */
.quick-add-section {
  padding: 0 32px 40px;
  max-width: 1200px;
  margin: 0 auto;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #f1f5f9;
  letter-spacing: -0.02em;
}

.widgets-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.widget-item {
  background: rgba(30, 41, 59, 0.8);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(148, 163, 184, 0.2);
  transition: all 0.2s ease;
}

.widget-item:hover {
  background: rgba(51, 65, 85, 0.9);
  border-color: rgba(148, 163, 184, 0.3);
  transform: translateY(-2px);
}

.widget-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.widget-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  color: #f1f5f9;
  font-size: 16px;
}

.widget-actions {
  display: flex;
  gap: 6px;
}

.widget-actions .el-button {
  padding: 6px 8px;
  font-size: 12px;
}

.widget-content {
  margin-bottom: 16px;
}

.widget-description {
  font-size: 14px;
  color: #94a3b8;
  line-height: 1.5;
  margin-bottom: 12px;
}

.widget-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.widget-version {
  font-size: 12px;
  color: #64748b;
}

.loading-container {
  padding: 60px 0;
}

.empty-container {
  padding: 80px 0;
  text-align: center;
  background: rgba(30, 41, 59, 0.6);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(148, 163, 184, 0.2);
}

.empty-container .el-empty__description {
  color: #94a3b8;
  font-size: 14px;
}

/* ==================== 响应式设计 ==================== */
@media (max-width: 768px) {
  .top-toolbar {
    padding: 16px 20px 0;
    flex-direction: column;
    gap: 12px;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .username {
    display: none;
  }
  
  .search-section {
    padding: 40px 16px 20px;
  }
  
  .search-container {
    max-width: 100%;
  }
  
  .unified-search-bar {
    flex-direction: column;
    gap: 6px;
    padding: 12px;
  }
  
  .search-engine-dropdown {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .engine-selector {
    min-width: 100%;
  }
  
  .search-input {
    margin: 0;
  }
  
  .search-button {
    width: 100%;
    padding: 12px;
  }
  
  .quick-add-section {
    padding: 0 16px 20px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .section-header h2 {
    font-size: 18px;
  }
  
  .search-title h1 {
    font-size: 24px;
  }
  
  .search-title p {
    font-size: 14px;
  }
  
  .widgets-grid {
    grid-template-columns: 1fr;
  }
  
  .widget-item {
    padding: 16px;
  }
}
</style>
